/**
 * @swagger
 * /api/room/land-analysis:
 *   get:
 *     tags:
 *       - 房屋管理
 *     summary: 获取房屋土地分析数据
 *     description: 分析房屋占地情况、土地利用率和规划配置
 *     responses:
 *       200:
 *         description: 成功获取土地分析数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                   description: 响应状态码
 *                 message:
 *                   type: string
 *                   example: "土地分析获取成功"
 *                   description: 响应消息
 *                 data:
 *                   type: object
 *                   properties:
 *                     officeLandInfo:
 *                       type: object
 *                       properties:
 *                         acres:
 *                           type: number
 *                           description: 办公用房土地面积（亩）
 *                         squareMeters:
 *                           type: string
 *                           description: 办公用房土地面积（平方米）
 *                         description:
 *                           type: string
 *                           description: 土地描述
 *                     totalLandInfo:
 *                       type: object
 *                       properties:
 *                         acres:
 *                           type: number
 *                           description: 总土地面积（亩）
 *                         squareMeters:
 *                           type: string
 *                           description: 总土地面积（平方米）
 *                         description:
 *                           type: string
 *                           description: 土地描述
 *                     buildingDensity:
 *                       type: string
 *                       description: 建筑密度（%）
 *                     floorAreaRatio:
 *                       type: string
 *                       description: 容积率
 *                     landEfficiency:
 *                       type: object
 *                       properties:
 *                         buildingAreaPerAcre:
 *                           type: string
 *                           description: 每亩建筑面积
 *                         constructionAreaPerAcre:
 *                           type: string
 *                           description: 每亩建设面积
 *                     baseData:
 *                       type: object
 *                       properties:
 *                         officeLandAcres:
 *                           type: number
 *                           description: 办公用房土地面积（亩）
 *                         totalLandAcres:
 *                           type: number
 *                           description: 总土地面积（亩）
 *                         totalBuildingArea:
 *                           type: number
 *                           description: 总建筑面积
 *                         totalConstructionArea:
 *                           type: number
 *                           description: 总建设面积
 *                     calculations:
 *                       type: object
 *                       properties:
 *                         buildingDensityDesc:
 *                           type: string
 *                           description: 建筑密度计算说明
 *                         floorAreaRatioDesc:
 *                           type: string
 *                           description: 容积率计算说明
 *                         conversionNote:
 *                           type: string
 *                           description: 换算说明
 *       500:
 *         description: 服务器内部错误
 */
const { query } = require('../../../lib/db')
const { success, error, handleResponse } = require('../../../lib/response')
const { withCors } = require('../../../lib/cors')

/**
 * 处理房屋土地分析请求
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function handler(req, res) {

  try {
    const sql = `
      SELECT 
        SUM(XGBGYFTDSM) as officeLandAcres,
        SUM(TJTDMS) as totalLandAcres,
        SUM(XXBXZJZMJ) as totalBuildingArea,
        SUM(ZJZMJ) as totalConstructionArea
      FROM wd_zcgk_bxzyhz
    `

    const result = await query(sql)
    
    if (!result || result.length === 0) {
      return handleResponse(res, error('暂无房产数据', 404))
    }

    const data = result[0]
    const officeLandAcres = parseFloat(data.officeLandAcres) || 0
    const totalLandAcres = parseFloat(data.totalLandAcres) || 0
    const totalBuildingArea = parseFloat(data.totalBuildingArea) || 0
    const totalConstructionArea = parseFloat(data.totalConstructionArea) || 0

    // 土地面积转换（1亩 ≈ 666.67平方米）
    const acreToSquareMeter = 666.67
    const officeLandSquareMeters = officeLandAcres * acreToSquareMeter
    const totalLandSquareMeters = totalLandAcres * acreToSquareMeter

    // 土地相关分析
    const landAnalysis = {
      // 办公用房占用土地
      officeLandInfo: {
        acres: officeLandAcres,
        squareMeters: officeLandSquareMeters.toFixed(2),
        description: '相关办公用房土地面积'
      },
      
      // 统计土地总面积
      totalLandInfo: {
        acres: totalLandAcres,
        squareMeters: totalLandSquareMeters.toFixed(2),
        description: '统计土地总面积'
      },
      
      // 建筑密度（建筑面积/土地面积）
      buildingDensity: totalLandSquareMeters > 0 ? 
        ((totalBuildingArea / totalLandSquareMeters) * 100).toFixed(2) : 0,
      
      // 容积率（总建筑面积/土地面积）
      floorAreaRatio: totalLandSquareMeters > 0 ? 
        (totalConstructionArea / totalLandSquareMeters).toFixed(2) : 0,
      
      // 土地利用效率指标
      landEfficiency: {
        buildingAreaPerAcre: totalLandAcres > 0 ? 
          (totalBuildingArea / totalLandAcres).toFixed(2) : 0,
        constructionAreaPerAcre: totalLandAcres > 0 ? 
          (totalConstructionArea / totalLandAcres).toFixed(2) : 0
      },
      
      // 原始数据
      baseData: {
        officeLandAcres,
        totalLandAcres,
        totalBuildingArea,
        totalConstructionArea
      },
      
      // 计算说明
      calculations: {
        buildingDensityDesc: `建筑面积${totalBuildingArea}㎡ / 土地面积${totalLandSquareMeters.toFixed(2)}㎡ × 100%`,
        floorAreaRatioDesc: `总建筑面积${totalConstructionArea}㎡ / 土地面积${totalLandSquareMeters.toFixed(2)}㎡`,
        conversionNote: '土地面积换算：1亩 ≈ 666.67平方米'
      }
    }

    return handleResponse(res, success(landAnalysis, '土地相关分析获取成功'))

  } catch (err) {
    console.error('土地分析接口错误:', err)
    return handleResponse(res, error('服务器内部错误', 500))
  }
}

export default withCors(handler, ['GET'])